import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/life/RefundDetailPage.dart';

class RefundListPage extends StatefulWidget {
  RefundListPage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _RefundListPage createState() => _RefundListPage();
}

class _RefundListPage extends State<RefundListPage> {

  // refund_reason 退货原因（0其他 1七天无理由退货 2产品质量问题 3发票问题 4不喜欢了/不爱了 5 拍错了/看错了 6 未按约定时间发货）
  // refund_type  类型（0退款，1退货，2,换货,  3退款不退货,  4取消订单）
  // refund_status 退换货状态（0:申请中 1：申请未通过 2：等待商家收货中 3：商家已收到货 4：商家已发货 5：客户已收货 6：退款成功 7：退货成功）
  List<Widget> items = [Text("1"), Text("2"),Text("3"),Text("4"),Text("5"),Text("6")];
 // List goods = [{"gid":100,"gname":"苹果","gprice":100},{"gid":101,"gname":"苹果1","gprice":200},{"gid":102,"gname":"苹果2","gprice":300},{"gid":103,"gname":"苹果3","gprice":400},];
  List goods=[];
  int page=1;
  // 构造函数
  _RefundListPage(){
    _onLoading();
  }
  // 上拉加载控制器
  RefreshController _refreshController = RefreshController(initialRefresh: false);
  // 刷新时调用
  void _onRefresh() async{
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }
  // 加载数据的函数
  void _onLoading() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var userId = prefs.getString("userId");
    // var userId = "6769";
    var x = await HttpUtil().get("/app/refunds/userSearchRefundInfo?limit=10&userId="+userId+"&page=${page}");
    page++;
    if(x['code']==200){
      goods.addAll(x['data']);
    }
    if(x['data'].length<1){
      _refreshController.loadNoData();
      return;
    }
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    if(mounted){
      setState(() {});
      _refreshController.loadComplete();
    }
  }

  Container _showGoods(item){
    return  Container(
      padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
            Row(children: [
              Icon(Icons.card_giftcard),
              Text("官方旗舰店")
            ],),
            Row(
              children: [
              item['refund_type']==0?  Icon(Icons.monetization_on_outlined,color: Colors.red,): Icon(Icons.restore,color: Colors.red,),
                // Text("退款")
                _showRefundType(item['refund_type'])
              ],
            )
          ],
          ),
          SizedBox(height: ScreenUtil().setWidth(10),),
          // CachedNetworkImage(imageUrl: Config.getInstance().getHost()+item['gimages']),
          Row(
            children: [
              CachedNetworkImage(imageUrl: Config.getInstance().getHost()+item['goods']['gimages'],width: ScreenUtil().setWidth(70),height: ScreenUtil().setWidth(70),),
              Column(
                children: [
                 Row(children: [Text(item['goods']['gname'])],) ,
                 Row(children: [Text(item['goods']['jianjie'])],) ,
                 Row(children: [item['odId']==null ? Text("") : Text("退款:￥${item['orderDetail']['odCost']}")],)
                ],
              )
            ],
          ),
          Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                  Container(child: _showRefundStatus(item['refund_status'],item['user_express_numbers']),margin:EdgeInsets.only(right: ScreenUtil().setWidth(10)) ,),
                Container(
                  padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
                  decoration: BoxDecoration(border: Border.all(width: 1,color: Colors.red),borderRadius: BorderRadius.all(Radius.circular(20))),
                  child: GestureDetector(
                    child: Text("查看详情"),
                    onTap: (){
                      MyRoute.push(RefundDetailPage(reid: item['id'], ));
                    },
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context , width: 464 , height: 820) ;
    return Scaffold(
      appBar: AppBar(
        title: Text("退款/售后"),
      ),
      body: SmartRefresher(
        enablePullDown: false,
        enablePullUp: true,
        header: WaterDropHeader(),
        footer: CustomFooter(
          builder: (BuildContext context,LoadStatus mode){
            Widget body ;
            if(mode==LoadStatus.idle){
              body =  Text("上拉加载");
            }
            else if(mode==LoadStatus.loading){
              body =  CupertinoActivityIndicator();
            }
            else if(mode == LoadStatus.failed){
              body = Text("加载失败！点击重试！");
            }
            else if(mode == LoadStatus.canLoading){
              body = Text("松手,加载更多!");
            }
            else{
              body = Text("没有更多数据了!");
            }
            return Container(
              height: 55.0,
              child: Center(child:body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: ListView.builder(
          itemBuilder: (c, i) => Card(child: _showGoods(goods[i])),
          // itemExtent: ScreenUtil().setHeight(180),
          itemCount: goods.length,
        ),
      ),
    );
  }
  // 动态显示售后类型
  Text _showRefundType(type) {
    var s = "退款";   // 默认退款
    if(type==1)
      s="退货";
    else if(type==2)
      s="换货";
    else if(type==3)
      s="退款不退货";
    else if(type==4)
      s="取消订单";
    return Text(s);
  }
  // 动态显示售后状态
  Text _showRefundStatus(status,express_numbers) {
    var s = "申请中";   // 默认退款
    if(status==1)
      s="申请未通过";
    else if(status==2)
      if(express_numbers==null || express_numbers==''){
        s='审核通过';
      }else{
        s='等待商家收货';
      }
    else if(status==3)
      s="商家已收货";
    else if(status==4)
      s="商家发货";
    else if(status==5)
      s="客户收货";
    else if(status==6)
      s="退款成功";
    else if(status==7)
      s="退货成功";
    return Text(s);
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}